/* eslint-disable prettier/prettier */
import { HttpException, HttpStatus } from '@nestjs/common';
import { async } from 'rxjs';
// import * as sharp from 'sharp';
// const { createCanvas, loadImage } = require('canvas');
import * as fs from 'fs';
import * as FormData from 'form-data';
import * as ProgressBar from 'progress';
import * as axios from 'axios';
import * as moment from 'moment'
import * as Path from 'path'
import * as concat from 'concat-stream'

export class ApiFail extends HttpException {
  constructor(code = 101, message = '失败',data=null) {
    super(
      {
        code,
        data,
        message,
      },
      HttpStatus.OK,
    );
  }
}

export function flatRoutes(routes, url, method) {
  for (let n = 0; n < routes.length; n++) {
    const element = routes[n];
    if (!element.children && element.childrens) {
      element.children = element.childrens;
    }
    if (element.children) {
      const childrenRef = element.children;
      for (let index = 0; index < childrenRef.length; index++) {
        const child = childrenRef[index];
        if (child instanceof Object && child.path) {
          if (child.path == url && child.jwt) {
            console.log('鉴权路由：', url);
            if (child.exclude) {
              if (!child.exclude.includes(method)) {
                return true;
              }
            } else {
              return true;
            }
          }
        }
      }
    }
  }

  return false;
}

export function readParame(filesPath, size = 400) {
  return new Promise(async(resolve) => {

  try {
    // const metadata = await sharp(filesPath).metadata();
    // console.log(metadata);
    // const ratio = metadata.width / metadata.height; // 获取宽高比
    // const width = size;
    // const height = parseInt((width / ratio)+"");
    // await sharp(filesPath).resize({
    //   width, height
    // }).extract({width: width-160, height:height-40, left: 80, top: 20 }) //四周去边
    // .toBuffer().then(async (buffer)=>{
    //   const dir = Path.dirname(filesPath);
    //   console.log('dir', dir);
    //   const ext = Path.extname(filesPath);
    //   const name = Path.basename(filesPath);
    //   const newPath = `${dir}/${name.split(".")[0]}_${size}${ext}`;
    //   await fs.writeFileSync(newPath, buffer);
    //   resolve({ filePath: newPath, fileName: `${name.split(".")[0]}_${size}${ext}` });
    // })
    
  } catch (error) {
    console.log(`An error occurred during processing: ${error}`);
  }
})
}
// export function readParame(filesPath, size = 400) {
//   var dimensions = sizeOf(filesPath);
//   let ratio = dimensions.width / dimensions.height; // 获取宽高比
//   let height = size,
//     width;
//   width = height * ratio;
//   try {
//     return CreateCanvas(width, height, filesPath, 1, size);
//   } catch (error) {
//     return null;
//   }
// }

const OrientationType = {
  1: 0, //（不翻转）
  3: 180, // 180度翻转
  6: 90, // 顺时针翻转90度
  8: -90, //  逆时针翻转90度
};

export function CreateCanvas(width, height, filepath, Orientation, size) {
  // let cvs = createCanvas(width, height);
  // let ctx = cvs.getContext('2d');
  // if ([3, 6, 8].includes(Orientation)) {
  //   ctx.translate(0, height);
  //   ctx.rotate((Number(OrientationType[Orientation]) * Math.PI) / 180);
  // }
  return new Promise((resolve) => {
    // loadImage(filepath).then(async (image) => {
    //   if ([3, 6, 8].includes(Orientation)) {
    //     ctx.drawImage(image, 0, 0, height, width);
    //   } else {
    //     ctx.drawImage(image, 0, 0, width, height);
    //   }
    //   const buffer = cvs.toBuffer('image/jpeg');
    //   const dir = Path.dirname(filepath);
    //   console.log('dir', dir);
    //   const ext = Path.extname(filepath);
    //   const name = Path.basename(filepath);
    //   const newPath = `${dir}/${name}_${size}${ext}`;
    //   await fs.writeFileSync(newPath, buffer);
      // resolve({ filePath: newPath, fileName: `${name.split(".")[0]}_${size}` });
      resolve({ filePath: "newPath", fileName: `` });
    });

  
}

export const jsonToParamsStr = (json_params) => {
  const params = Object.keys(json_params)
    .map(function (key) {
      // body...
      return (
        encodeURIComponent(key) + "=" + encodeURIComponent(json_params[key])
      );
    })
    .join("&");
  return params;
};

/**
 *  POST /api/Avatar/GetAliDM HTTP/1.1
Authorization: SHA256 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcGVuaWQiOiJvQUoyNTZRaWdXbzZTTHhrMjJQSG5vN05sazlFIiwiYXBwX29wZW5pZCI6Im9BSjI1NlFpZ1dvNlNMeGsyMlBIbm83TmxrOUUiLCJhcHBfY29kZSI6IkhFQUQiLCJpZCI6MzUyODUzLCJuaWNrbmFtZSI6IuWwj-Wwj-aItOWFiOeUnyIsInVzZXJfcGhvbmUiOm51bGwsImhlYWRpbWd1cmwiOiJodHRwczovL3RoaXJkd3gucWxvZ28uY24vbW1vcGVuL3ZpXzMyLzUwekFMTVZSSGdzZzZRVWliaWFUemliSHFtcE1ZSFMwT3pWcVRsWXJkQkxmanhvTWljSE43UnVVMk1IVDVqdzhnVUpvaFVuTWR3MTl2ekt2RTNaNFdWcEhody8xMzIiLCJzZXgiOjAsImF1ZGlvX3RpbWUiOjE4MDAsImV4cCI6MTcxNjgxOTYzNS40MDUyNTkxfQ.E7lQStfy_UpnbcB8iemVqCmSOVygmqNduzHm_Q3KQto
Content-Type: multipart/form-data; boundary=1cce85e4-80b9-4210-be4f-d0c5f37a2609
Content-Length: 105177
Host: head.jcor.cn
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/4.9.0

Content-Disposition: form-data; name="coverFile"; filename="CROP_20231128005312282.jpg"
Content-Type: image/*
Content-Length: 104955
 * @param filePath 
 * @returns 
 */
export async function thirdUpload(action="GetAliDM", filePath) {
  const url = `http://head.jcor.cn/api/Avatar/${action}`;

  const formData = new FormData();
  const fileName = Path.basename(filePath);
  const Authorization =
    'SHA256 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcGVuaWQiOiJvQUoyNTZRaWdXbzZTTHhrMjJQSG5vN05sazlFIiwiYXBwX29wZW5pZCI6Im9BSjI1NlFpZ1dvNlNMeGsyMlBIbm83TmxrOUUiLCJhcHBfY29kZSI6IkhFQUQiLCJpZCI6MzUyODUzLCJuaWNrbmFtZSI6IuWwj-Wwj-aItOWFiOeUnyIsInVzZXJfcGhvbmUiOm51bGwsImhlYWRpbWd1cmwiOiJodHRwczovL3RoaXJkd3gucWxvZ28uY24vbW1vcGVuL3ZpXzMyLzUwekFMTVZSSGdzZzZRVWliaWFUemliSHFtcE1ZSFMwT3pWcVRsWXJkQkxmanhvTWljSE43UnVVMk1IVDVqdzhnVUpvaFVuTWR3MTl2ekt2RTNaNFdWcEhody8xMzIiLCJzZXgiOjAsImF1ZGlvX3RpbWUiOjE4MDAsImV4cCI6MTcxNjgxOTYzNS40MDUyNTkxfQ.E7lQStfy_UpnbcB8iemVqCmSOVygmqNduzHm_Q3KQto';

  formData.append('coverFile', fs.createReadStream(filePath));
  console.log(filePath);
  const headers = formData.getHeaders();
  const config = {
    ...headers,
    'Content-Type':
      'multipart/form-data;boundary=----WebKitFormBoundaryVCFSAonTuDbVCoAN;image/*',
    Authorization: Authorization,
  };
  // formData.getLength(async function (err, length) {
  //   if (err) {
  //     return;
  //   }
  //   //设置长度，important!!!
  //   config['Content-length'] = length;
  // });
  const progressBar = new ProgressBar(
    `Uploading ${fileName} [:bar] :percent`,
    {
      total: fs.statSync(filePath).size,
      width: 40,
      complete: '=',
      incomplete: ' ',
    },
  );
  // 转buffer流才能搞定 一般上传文件不需要
  return new Promise(resole=>{
    formData.pipe(
      concat({ encoding: 'buffer' }, async (data) => {
        const response = await axios.default.post(url, data, {
          headers: config,
          onUploadProgress: (progressEvent) => {
            progressBar.tick(progressEvent.loaded);
          },
        });
        try {
          console.log(`Upload complete:`);
          console.log(response.data);
          resole(response.data.Data)
        } catch (error) {
          resole(null)
        }
      }),
    );
  })

}
